package com.chenhj.interceptor;

import java.util.List;

import javax.xml.soap.SOAPException;

import org.apache.cxf.binding.soap.SoapMessage;
import org.apache.cxf.headers.Header;
import org.apache.cxf.interceptor.Fault;
import org.apache.cxf.phase.AbstractPhaseInterceptor;
import org.apache.cxf.phase.Phase;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import com.chenhj.utils.EncryptUtil;

public class ValidateInInterceptor extends AbstractPhaseInterceptor<SoapMessage> {
	
	private Logger logger = LogManager.getLogger(ValidateInInterceptor.class);
	public ValidateInInterceptor() {
		// 指定该拦截器在哪个阶段被激发
		// 在调用方法之前调用自定义拦截器
		super(Phase.PRE_INVOKE);
	}

	@Override
	public void handleMessage(SoapMessage message) throws Fault {
		List<Header> headers = message.getHeaders(); // 根据soap消息获取头部
		if (headers == null || headers.size() == 0) {
			throw new Fault(new SOAPException("SOAP消息头格式不对！"));
		}
		Header firstHeader = headers.get(0); 
		Element elm = (Element) firstHeader.getObject();
		NodeList usernameList = elm.getElementsByTagName("username");
		NodeList passwordList = elm.getElementsByTagName("password");
		if (usernameList.getLength() != 1) {
			throw new Fault(new IllegalArgumentException("用户名格式不对"));
		}

		if (passwordList.getLength() != 1) {
			throw new Fault(new IllegalArgumentException("密码格式不对"));
		}
		// 获取元素的文本内容
		String username = usernameList.item(0).getTextContent();
		String password = passwordList.item(0).getTextContent();
		password = EncryptUtil.strToEncrypt("123456", "MD5", 1024, username);
		System.out.println("password="+password);
		if(!"chenhj".equals(username) || !password.equals(password)){
			logger.info("用户名或密码不对！");
			throw new Fault(new IllegalArgumentException("用户名或密码不对！"));
		}else{
			logger.info(username+"用户验证通过，可以访问!");
		}
	}
}
